/*
 * @Descripttion: 
 * @version: 1.0
 * @Author: Sam
 * @Date: 2022-03-26 02:58:38
 * @LastEditors: Sam
 * @LastEditTime: 2022-11-30 15:32:41
 */
import axios from 'axios'
import { Message,Loading } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // timeout: 5000 // request timeout
})
const loadingService = () => {
  return Loading.service({
    lock: true,
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.1)'
  })
}
// request interceptor
service.interceptors.request.use(
  config => {
    store.commit('settings/SET_AJAX_BUTTON', true)
    // do something before request is sent
    if (store.getters.token) {
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }

    loadingService()
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    loadingService().close();
    store.commit('settings/SET_AJAX_BUTTON', false);
    const res = response.data
    if(res.code === 103 || res.code === 105 ){
      Message({
        message: '登录超时，请重新登录',
        type: 'error',
        duration: 1 * 1000
      })
      store.dispatch('user/logout').then(() => {
        location.reload()
      })
    }
    if (res.code == 0  ||res.code === 2 || !res.code ||  res.code === 10501) {
      // token 权限 错误码
        Message({
          message: res.msg || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
    
  },
  error => {
    store.commit('settings/SET_AJAX_BUTTON', false);
    console.log('err' + error) // for debug
    Message({
      message: error.msg || '网络错误',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
